package tw.asap.plus.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import jp.wasabeef.fresco.processors.BlurPostprocessor;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.CartBean;
import tw.asap.plus.entity.User;
import tw.asap.plus.entity.request.ShopKey;
import tw.asap.plus.entity.response.GoodsInfo;
import tw.asap.plus.entity.response.GoodsInfoNV;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.entity.response.ShopInfo;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.MerchantService;
import tw.asap.plus.network.service.UserService;
import tw.asap.plus.presenter.CartPresenter;
import tw.asap.plus.presenter.CartPresenterImpl;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.adapter.PinedSectionAdapter;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.ui.custom.CartView;
import tw.asap.plus.ui.fragment.GoodsListFragment;
import tw.asap.plus.ui.fragment.MerchantInfoFragment;
import tw.asap.plus.utils.ScreenUtil;
import tw.asap.plus.utils.T;
import tw.asap.plus.utils.Toaster;
import tw.asap.plus.utils.Utils;

/**
 * Created by Yax on 15/11/4.
 */
public class MerchantActivity extends AsapBaseActivity {


    @InjectView(R.id.myAppbar)
    AppBar myAppbar;
    @InjectView(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @InjectView(R.id.tv_merchant_info)
    TextView tvMerchantInfo;
    @InjectView(R.id.tv_merchant_broadcast)
    TextView tvMerchantBroadcast;
    @InjectView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @InjectView(R.id.tabs)
    TabLayout tabLayout;
    @InjectView(R.id.appbar)
    AppBarLayout appbar;
    @InjectView(R.id.viewpager)
    ViewPager viewPager;
    @InjectView(R.id.fm)
    CartView cartView;
    @InjectView(R.id.main_content)
    CoordinatorLayout mainContent;

    ShopIndex.ShopEntity shopEntity;
    ShopInfo shopDetailInfo;

    int prePosition = 0;
    @InjectView(R.id.icon_merchant)
    SimpleDraweeView iconMerchant;

    GoodsListFragment goodsListFragment;
    @InjectView(R.id.merchant_head_bg)
    SimpleDraweeView merchantHeadBg;
    private static CartPresenter presenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchant_coordinat);
        ButterKnife.inject(this);

        shopEntity = getIntent().getParcelableExtra("SHOP_ENTITY");
        initData(shopEntity);
        setUpCartList();
        initViews();
    }

    private void setUpCartList() {

    }

    public ShopIndex.ShopEntity getShopEntity() {
        return shopEntity;
    }


    private void fillShopData(ShopInfo data) {
        tvMerchantName.setText(data.getName().concat("(").concat(data.getSubname()).concat(")"));
        StringBuilder sb = new StringBuilder();
        sb.append("起送 $ ").append(Utils.getFormatAmt(data.getShipping_base())).append("    配送 $ ").append(Utils.getFormatAmt(data.getShipping_price()))
                .append("    平均").append(data.getShipping_times()).append("分钟");
        tvMerchantInfo.setText(sb.toString());
        tvMerchantBroadcast.setText(data.getBulletin());
        iconMerchant.setImageURI(Uri.parse(data.getLogo()));

        if (!TextUtils.isEmpty(data.getLogo())) {
            BlurPostprocessor processor = new BlurPostprocessor(this, 25);
            ImageRequest request =
                    ImageRequestBuilder.newBuilderWithSource(Uri.parse(data.getLogo()))
                            .setPostprocessor(processor)
                            .build();

            PipelineDraweeController controller =
                    (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setImageRequest(request)
                            .setOldController(merchantHeadBg.getController())
                            .build();
            merchantHeadBg.setController(controller);
        }
    }


    private void fillGoodsData(ArrayList<PinedSectionAdapter.GoodsItem> sectionList, ArrayList<PinedSectionAdapter.GoodsItem> itemList) {
        if (viewPager != null) {
            setupViewPager(viewPager, itemList, sectionList);
            tabLayout.setupWithViewPager(viewPager);
        }
    }

    public boolean checkLoginState() {
        if (!User.hasLogin()) {
            Toaster.s(this, getString(R.string.user_not_login));
            startActivity(new Intent(this, LoginAsapActivity.class));
            return false;
        }
        return true;
    }

    private void initViews() {

        int api = Build.VERSION.SDK_INT;

        if (api >= 21) {
            int topGap = ScreenUtil.dip2px(this, 25);
            myAppbar.setPadding(0, topGap, 0, 0);
        }
        myAppbar.setLeftNavigation(0, v -> {
            finish();
        });
        if (shopEntity.getIs_star().equals("0")) {
            myAppbar.setRightImage(R.drawable.icon_no_collect);
        } else {
            myAppbar.setRightImage(R.drawable.icon_collected);
        }

        myAppbar.setRightClickEvent(v -> {

            if (checkLoginState()) {
                if (shopEntity.getIs_star().equals("0")) {
                    collectShop(true);
                } else {
                    collectShop(false);
                }
            }
        });


        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                T.d("onPageScrolled");
            }

            @Override
            public void onPageSelected(int position) {
                T.d("onPageSelected : id= " + position);

                if (prePosition == 0 && position == 1) {
                    cartView.hideCartBar();
                } else if (prePosition == 1 && position == 0) {
                    cartView.showCartBar();
                }

                prePosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                T.d("onPageScrollStateChanged");

            }
        });
    }

    public static CartPresenter getCartPresenter() {
        return presenter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter = null;
    }

    private void setupViewPager(ViewPager viewpager, ArrayList<PinedSectionAdapter.GoodsItem> itemList, ArrayList<PinedSectionAdapter.GoodsItem> secionList) {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        goodsListFragment = GoodsListFragment.newInstance(secionList, itemList);

        presenter = new CartPresenterImpl(this, shopEntity.getShopkey());
        presenter.bindView(cartView, () -> {
            if (presenter.getCartGoodsList() != null) {
                ArrayList<CartBean> list = (ArrayList<CartBean>) presenter.getCartGoodsList();
                Intent intent = new Intent(this, OrderConfirmActivity.class);
                intent.putExtra("GOODS_INFO", list);
                intent.putExtras(getIntent());
                startActivity(intent);
            }
        });
        goodsListFragment.bindCartView(presenter);
        adapter.addFragment(goodsListFragment, getString(R.string.buy));
        adapter.addFragment(MerchantInfoFragment.newInstance(shopDetailInfo), getString(R.string.merchant));
        viewpager.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (presenter != null && cartView != null) {
            presenter.bindView(cartView, () -> {
                if (presenter.getCartGoodsList() != null) {
                    ArrayList<CartBean> list = (ArrayList<CartBean>) presenter.getCartGoodsList();
                    Intent intent = new Intent(this, OrderConfirmActivity.class);
                    intent.putExtra("GOODS_LIST", list);
                    intent.putExtras(getIntent());
                    startActivity(intent);
                }
            });
            presenter.notifyData();
        }
    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

        public Adapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }


    private void initData(ShopIndex.ShopEntity shopEntity) {

        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<ShopInfo>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<ShopInfo>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);
                subscriber.onNext(service.getShopInfo(new ShopKey(shopEntity.getShopkey())));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<ShopInfo>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<ShopInfo> shopInfoResponseDataWrapper) {
                        shopDetailInfo = shopInfoResponseDataWrapper.data;
                        fillShopData(shopInfoResponseDataWrapper.data);
//                        initGoodsData();
                        initNewGoodsData();
                    }
                });
    }


    private void collectShop(boolean isCollect) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper> subscriber) {
                UserService service = creator.getService(UserService.class);
                if (isCollect) {
                    subscriber.onNext(service.collectShop(new ShopKey(shopEntity.getShopkey())));
                } else {
                    subscriber.onNext(service.cancelCollect(new ShopKey(shopEntity.getShopkey())));
                }
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper response) {
                        if (response.respcd.equals(ConstValue.RESPCD)) {
                            if (isCollect) {
                                myAppbar.setRightImage(R.drawable.icon_collected);
                                shopEntity.setIs_star("1");
                                Toaster.s(MerchantActivity.this, getString(R.string.collect_success));
                            } else {
                                myAppbar.setRightImage(R.drawable.icon_collection);
                                shopEntity.setIs_star("0");
                                Toaster.s(MerchantActivity.this, getString(R.string.uncollect_success));
                            }
                        }
                    }
                });
    }

    private void initNewGoodsData() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<GoodsInfoNV>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<GoodsInfoNV>>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);

                ResponseDataWrapper<List<GoodsInfoNV>> responseDataWrapper = service.getNewGoodsList(new ShopKey(shopEntity.getShopkey()));
                subscriber.onNext(responseDataWrapper);
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<GoodsInfoNV>>>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {
                                   T.e(e.toString());
                               }

                               @Override
                               public void onNext(ResponseDataWrapper<List<GoodsInfoNV>> goodsInfoList) {
                                   List<GoodsInfoNV> originList = goodsInfoList.data;
                                   //Data transfer
                                   if (originList != null && originList.size() > 0) {
                                       ArrayList<PinedSectionAdapter.GoodsItem> goodsItemList = new ArrayList<>();
                                       ArrayList<PinedSectionAdapter.GoodsItem> sectionItemList = new ArrayList<>();
                                       int listPosition = 0;
                                       for (int i = 0; i < originList.size(); i++) {
                                           PinedSectionAdapter.GoodsItem classItem =
                                                   new PinedSectionAdapter.GoodsItem(PinedSectionAdapter.GoodsItem.SECTION, originList.get(i).getItem_class(), null);
                                           classItem.sectionPosition = i;
                                           classItem.listPosition = listPosition++;
                                           goodsItemList.add(classItem);
                                           sectionItemList.add(classItem);
                                           if (originList.get(i).getItem_list() != null && originList.get(i).getItem_list().size() > 0) {
                                               for (GoodsInfoNV.ItemListEntity goods : originList.get(i).getItem_list()) {
                                                   PinedSectionAdapter.GoodsItem goodsItem =
                                                           new PinedSectionAdapter.GoodsItem(PinedSectionAdapter.GoodsItem.ITEM, goods.getTitle(), goods);
                                                   goodsItem.sectionPosition = i;
                                                   goodsItem.listPosition = listPosition++;
                                                   goodsItemList.add(goodsItem);
                                               }
                                           }
                                       }
                                       fillGoodsData(sectionItemList, goodsItemList);
                                   }
                               }
                           }
                );
    }

    private void initGoodsData() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<GoodsInfo>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<GoodsInfo>>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);

                ResponseDataWrapper<List<GoodsInfo>> responseDataWrapper = service.getGoodsList(new ShopKey(shopEntity.getShopkey()));
                subscriber.onNext(responseDataWrapper);
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<GoodsInfo>>>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {
                                   T.e(e.toString());
                               }

                               @Override
                               public void onNext(ResponseDataWrapper<List<GoodsInfo>> goodsInfoList) {
                                   List<GoodsInfo> originList = goodsInfoList.data;
                                   //Data transfer
                                   if (originList != null && originList.size() > 0) {
                                       ArrayList<PinedSectionAdapter.GoodsItem> goodsItemList = new ArrayList<>();
                                       ArrayList<PinedSectionAdapter.GoodsItem> sectionItemList = new ArrayList<>();
                                       int listPosition = 0;
                                       for (int i = 0; i < originList.size(); i++) {
                                           PinedSectionAdapter.GoodsItem classItem =
                                                   new PinedSectionAdapter.GoodsItem(PinedSectionAdapter.GoodsItem.SECTION, originList.get(i).getItem_class(), null);
                                           classItem.sectionPosition = i;
                                           classItem.listPosition = listPosition++;
                                           goodsItemList.add(classItem);
                                           sectionItemList.add(classItem);
                                           if (originList.get(i).getItem_list() != null && originList.get(i).getItem_list().size() > 0) {
                                               for (GoodsInfo.ItemListEntity goods : originList.get(i).getItem_list()) {
//                                                   PinedSectionAdapter.GoodsItem goodsItem =
//                                                           new PinedSectionAdapter.GoodsItem(PinedSectionAdapter.GoodsItem.ITEM, goods.getTitle(), goods);
//                                                   goodsItem.sectionPosition = i;
//                                                   goodsItem.listPosition = listPosition++;
//                                                   goodsItemList.add(goodsItem);
                                               }
                                           }
                                       }
                                       fillGoodsData(sectionItemList, goodsItemList);
                                   }
                               }
                           }

                );
    }
}
